import csv, chardet, os
from django.conf import settings
from vegmapportal.models import Polygon, Park, Photo
from django.core.files import File
inputFile=settings.INPUT_FILE
photosDir=settings.PHOTOS_DIR

def importPolygons(inputFile=inputFile):
    polygonFile = open(inputFile,'r')
    polygonReader = csv.reader(polygonFile)
    headers = polygonReader.next()
    header = dict(zip(headers, range(len(headers))))
    
    for polygonLine in polygonReader:

        veg_notes=polygonLine[header['Vegetation Notes']]
        if veg_notes:
            encoding=chardet.detect(veg_notes)
            veg_notes=veg_notes.decode(encoding['encoding'])

        soil_notes=polygonLine[header['Soil Notes']]
        if soil_notes:
            encoding=chardet.detect(soil_notes)
        print encoding
        soil_notes=soil_notes.decode(encoding['encoding'])

        park_code=polygonLine[header['Unit Code']]
      
        park=Park.objects.get_or_create(code=park_code.lower())[0]
        
        nonLookupAttribs={'veg_notes':veg_notes, 'soil_notes':soil_notes, 'park':park}
        
        new_id=polygonLine[header['New Poly ID']]
        Polygon.objects.get_or_create(new_id=new_id, defaults=nonLookupAttribs)
        

def checkFilenameInDir(polygon, direction, directory):
    xpctdFilename='_'.join((polygon.park.code.upper(), polygon.new_id, direction))
    try:
        for filename in os.listdir(directory):
            if xpctdFilename in filename or xpctdFilename.lower() in filename:
                res=os.path.join(directory,filename)
                return (filename, res)
    except:
        return None
                            

def importPhotosForPolygon(polygon, photosDir=settings.PHOTOS_DIR):
    polyPhotosDirs=[]
    polyPhotosDirs.append(os.path.join(settings.MEDIA_ROOT,'photos'))
    polyPhotosDirs.append(os.path.join(photosDir,'Polygon photos',polygon.park.code.upper()))
    polyPhotosDirs.append(os.path.join(photosDir,'Polygon photos',polygon.park.code.upper(),'Transferred_to_SS_SODN'))
    polyPhotosDirs.append(os.path.join(photosDir,'Polygon photos',polygon.park.code.upper(),'Transfer_to_SS_SODN'))
    print polyPhotosDirs
    pathList=[]
    for direction in ('N','E','S','W'):
        for directory in polyPhotosDirs:
            out=checkFilenameInDir(polygon, direction, directory)
            if out:
                print out[1]    
                newPhoto=Photo(polygon=polygon, direction=direction)
                try:
                    newPhoto.original_image.save(out[0],File(open(out[1],'rb')))
                except:
                    print 'failed on'+unicode(polygon)
                break

def importAllPhotos():
    for poly in Polygon.objects.all():
        if poly.photo_set.count()!=4:
            print 'importing photos for '+unicode(poly)
            importPhotosForPolygon(poly)
        else:
            unicode(poly)+' already has photos'